import { is } from 'bpmn-js/lib/util/ModelUtil';
import { CheckboxEntry, isCheckboxEntryEdited } from '@bpmn-io/properties-panel';
import { useService } from 'bpmn-js-properties-panel';

/**
 * @typedef { import('@bpmn-io/properties-panel').EntryDefinition } Entry
 */

/**
 * @returns {Array<Entry>} entries
 */
export function ExecutableProps(props) {
  const { element } = props;

  if (!is(element, 'bpmn:Process') && !hasProcessRef(element)) {
    return [];
  }

  return [
    {
      id: 'isExecutable',
      component: Executable,
      isEdited: isCheckboxEntryEdited,
    },
  ];
}

function Executable(props) {
  const { element } = props;

  const modeling = useService('modeling');
  const commandStack = useService('commandStack');
  const translate = useService('translate');

  let getValue, setValue;

  setValue = (value) => {
    modeling.updateProperties(element, {
      isExecutable: value,
    });
  };

  getValue = (element) => {
    return element.businessObject.isExecutable;
  };

  // handle properties on processRef level for participants
  if (is(element, 'bpmn:Participant')) {
    const process = element.businessObject.get('processRef');

    setValue = (value) => {
      commandStack.execute('element.updateModdleProperties', {
        element,
        moddleElement: process,
        properties: {
          isExecutable: value,
        },
      });
    };

    getValue = () => {
      return process.get('isExecutable');
    };
  }

  return CheckboxEntry({
    element,
    id: 'isExecutable',
    label: translate('Executable'),
    getValue,
    setValue,
  });
}

// helper /////////////////////

function hasProcessRef(element) {
  return is(element, 'bpmn:Participant') && element.businessObject.get('processRef');
}
